<template>
    <div class="ticket-list-container">
        <van-loading v-if="loadingStatus" size="48px" vertical>
            查询中...
        </van-loading>
        <p class="title">会话记录和工单状态</p>
        <div class="ticket-wrapper">
            <TicketFilter
                :tickets="ticketList"
                @model="onModel"
                @active="onActive"
                @time="onTime"
            />
            <div v-if="filterTickets.length > 0" class="session-wrapper">
                <TicketItem
                    v-for="(item, index) in filterTickets"
                    :key="item.id"
                    :ticket="item"
                    :showDivider="index < ticketList.length - 1"
                    @showTicketInfo="onTicketInfo"
                    @showTalkInfo="onTalkInfo"
                />
            </div>
            <div v-else class="empty-wrapper">
                <p class="image"></p>
                <p class="label">暂无会话记录</p>
            </div>
        </div>
        <TicketInfo
            :show="showTicketInfo"
            :ticket="curTicket"
            @close="() => (showTicketInfo = false)"
        />
        <TalkInfo
            :show="showTalkInfo"
            :ticket="curTicket"
            @close="() => (showTalkInfo = false)"
        />
        <SystemError
            :show="showSystemError"
            @close="
                () => {
                    showSystemError = false;
                }
            "
        />
    </div>
</template>

<script>
import { mapState } from "vuex";
import TicketFilter from "./TicketFilter.vue";
import TicketItem from "./TicketItem.vue";
import TicketInfo from "./TicketInfo.vue";
import TalkInfo from "./TalkInfo.vue";
import SystemError from "../error/SystemError.vue";
import { isBetweenDate, formatMindrayTime, getDuration } from "../../lib/util";
import { getTicketList, getTalkInfo, getTicketDetail } from "../../api/api";
// import { tickets } from "../../mock/tickets";
export default {
    components: { TicketFilter, TicketItem, TicketInfo, TalkInfo, SystemError },
    data() {
        return {
            showSystemError: false,
            showTicketInfo: false,
            showTalkInfo: false,
            curTicket: {},
            filterTickets: [],
            ticketList: [],
            loadingStatus: false, //是否显示loading
        };
    },
    computed: {
        ...mapState("user", ["id", "openid", "isLogin"]),
    },
    watch: {
        isLogin(newVal, oldVal) {
            if (newVal === oldVal) return;
            if (!newVal) {
                this.ticketList = [];
                this.filterTickets = [];
            }
        },
    },
    created() {},
    mounted() {
        // this.parseTicketData(tickets);
        this.getTicketList();
    },
    methods: {
        getTicketList() {
            this.loadingStatus = true;
            this.ticketList = [];
            this.filterTickets = [];
            getTicketList(this.openid)
                .then((resp) => {
                    const { code, data } = resp.data;
                    if (code === "0000" && data) {
                        this.parseTicketData(data);
                    } else {
                        console.warn("get ticket list error ", resp);
                        this.showSystemError = true;
                    }
                    this.loadingStatus = false;
                })
                .catch((err) => {
                    console.error("get ticket list error ", err);
                    this.showSystemError = true;
                    this.loadingStatus = false;
                });
        },
        getTalkInfo(ticket) {
            this.curSessions = [];
            this.curTicketId = ticket.id;
            getTalkInfo(ticket.id)
                .then((resp) => {
                    const { code, data } = resp.data;
                    if (code === "0000" && data) {
                        ticket.talkTime = [];
                        data.map((item) => {
                            if (item.session) {
                                const talkTime = {};
                                const {
                                    createdAt,
                                    closedAt,
                                    invitations,
                                    sessionId,
                                } = item.session;
                                talkTime.sessionId = sessionId;
                                talkTime.begin =
                                    this.$moment(createdAt).format(
                                        "YYYY-MM-DD HH:mm"
                                    );
                                talkTime.end = closedAt;
                                if (invitations && invitations.length > 0) {
                                    const result =
                                        this.parseInvitations(invitations);
                                    const { acceptedAt, agent } = result;
                                    talkTime.agentId = agent;

                                    talkTime.duration =
                                        acceptedAt && closedAt
                                            ? getDuration(acceptedAt, closedAt)
                                            : "-";
                                }
                                ticket.talkTime.push(talkTime);
                            }
                        });

                        this.curTicket = ticket;
                        this.showTalkInfo = true;
                    } else {
                        console.warn("get talk info error ", resp);
                        this.showSystemError = true;
                    }
                })
                .catch((err) => {
                    console.error("get talk info error ", err);
                    this.showSystemError = true;
                });
        },
        getTicketDetail(ticket) {
            getTicketDetail(ticket.id)
                .then((resp) => {
                    const { code, data } = resp.data;
                    if (code === "0000" && data) {
                        // ZKH_NAME 客户名称
                        // this.curTicket = data;
                        // this.showTicketInfo = true;
                        //  "SALES_OFFICE_DESC": "深圳分公司", 所属分公司描述
                        ticket.company = data.SALES_OFFICE_DESC;
                        this.curTicket = ticket;
                        this.showTicketInfo = true;
                    } else {
                        console.warn("get ticket detail error ", resp);
                        this.showSystemError = true;
                    }
                })
                .catch((err) => {
                    console.error("get ticket detail error ", err);
                    this.showSystemError = true;
                });
        },
        onTicketInfo(ticket) {
            this.getTicketDetail(ticket);
        },
        onTalkInfo(ticket) {
            this.getTalkInfo(ticket);
        },
        onModel(model) {
            this.filterTickets = [];
            this.filterTickets = this.ticketList.filter(
                (item) => item.model === model
            );
        },
        onActive(index) {
            if (index === 0) {
                this.filterTickets = [...this.ticketList];
            }
        },
        onTime(time) {
            this.filterTickets = [];
            this.filterTickets = this.ticketList.filter((item) =>
                isBetweenDate(item.talkTime, time.begin, time.end)
            );
        },
        parseTicketData(data) {
            this.ticketList = [];
            this.filterTickets = [];
            if (!data || data.length <= 0) return;
            data.map((item) => {
                item.ticketId = item.id; // 工单号
                // item.model = item.PROD_MODEL;
                item.ticketStatusText = item.ZSLD_TEXT || "-";
                item.status = ["派工完成", "转FSM平台派工"].includes(
                    item.ZSLD_TEXT
                )
                    ? 1
                    : 0;
                item.engineerName = item.ZGCS_NAME || "-"; // 工程师名字
                item.engineerPhone = item.ZGCS_TEL || "-"; // 工程师手机号
                item.dispatchedTime = formatMindrayTime(item.ZPG_DATE); // 已派工时间 20221008080101
                item.orderTime = formatMindrayTime(item.ZYY_DATE); // 已预约时间 20221008111005
                item.startTime = formatMindrayTime(item.ZXCFW_BEGIN_DATE); // 现场服务开始时间 20221010T110001 20130208T080910
                item.visitTime = formatMindrayTime(item.ZYYSM_DATE); // 预约上门时间 20221010110000
                item.finishTime = formatMindrayTime(item.ZWGQR_DATE); // 完工确认 20221010110000

                if (item.orderSessions && item.orderSessions.length > 0) {
                    item.talkTime = [];
                    item.orderSessions.map((session) => {
                        if (session.session) {
                            const { createdAt, closedAt } = session.session;
                            item.talkTime.push({
                                begin: createdAt,
                                end: closedAt,
                            });
                            session.session.duration = getDuration(
                                createdAt,
                                closedAt
                            );
                            session.session.createdAt =
                                this.$moment(createdAt).format(
                                    "YYYY-MM-DD HH:mm"
                                );
                        }
                    });
                }
                if (item.talkTime.length > 0) {
                    this.ticketList.push(item);
                    this.filterTickets.push(item);
                }
            });
        },
        parseInvitations(invitations) {
            const agents = [];
            const result = { acceptedAt: null, agent: "" };
            if (!invitations || invitations.length <= 0) {
                return result;
            }
            invitations.map((invitation) => {
                if (!result.acceptedAt && invitation.acceptedAt) {
                    result.acceptedAt = invitation.acceptedAt;
                }
                if (invitation.invitationHistoryStatuses) {
                    invitation.invitationHistoryStatuses.map((item) => {
                        if (!agents.includes(item.assignedAgentId)) {
                            agents.push(item.assignedAgentId);
                        }
                    });
                }
            });
            result.agent = agents.join(",");
            return result;
        },
    },
};
</script>

<style lang="less" scoped>
.ticket-list-container {
    min-height: calc(100vh - 172px - env(safe-area-inset-bottom));
    text-align: left;
    padding: 16px 16px 0 16px;
    box-sizing: border-box;
    background: #f7f7f7;

    .title {
        font-size: 14px;
        font-weight: 400;
        color: #5b6366;
        line-height: 20px;
        margin: 0;
    }

    .ticket-wrapper {
        background: #ffffff;
        box-shadow: 0px 6px 24px 0px rgba(0, 0, 0, 0.08);
        border-radius: 10px;
        width: 100%;
        height: fit-content;
        min-height: calc(100vh - 218px - env(safe-area-inset-bottom));
        box-sizing: border-box;
        margin-top: 10px;

        .empty-wrapper {
            height: calc(100% - 50px);
            min-height: calc(100vh - 300px - env(safe-area-inset-bottom));
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            .image {
                width: 126px;
                height: 104px;
                background-image: url("../../assets/img/empty.png");
                background-size: 126px 104px;
                display: inline-block;
                background-position: center;
                background-repeat: no-repeat;
                margin-left: auto;
                margin: 0;
            }
            .label {
                font-size: 13px;
                font-weight: 400;
                color: #a6a6a6;
                line-height: 18px;
                margin: 0;
                margin-top: 12px;
            }
        }
    }
    .van-loading {
        position: absolute;
        left: calc(50% - 26px);
        top: 50%;
    }
}
</style>
